//
//  TIMHepler.m
//  IMDemo
//
//  Created by KwokChun Cheung on 16/3/18.
//  Copyright © 2016年 eenet. All rights reserved.
//

#import "TIMHepler.h"
#import <ImSDK/ImSDK.h>
#import <ImSDK/TIMMessage.h>

@implementation TIMHepler

-(instancetype)init{
    if (self = [super init]) {
        
    }
    return self;
}

-(void)loginServiceWithAccount:(NSString *)account{
    
    NSString *urlString = [NSString stringWithFormat:@"http://tt.api.ouchgzee.com/androidphone/login/gjtLogin.do?LoginName=%@&Password=ODg4ODg4&rule=standard&eeIM=Y", account];
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    req.HTTPMethod = @"GET";
    [req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *mySession = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [mySession dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            
            NSError *parseError = nil;
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
            
            if(parseError) {
                NSLog(@"JSON解析错误");
                return;
            }
            
            NSString *imID = result[@"imObj"][@"IM_USERID"];
            NSString *sig = result[@"imObj"][@"USER_SIG"];
            
            [self loginIMWithId:imID andSig:sig];
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:imID forKey:@"IM_USERID"];
            [userDefaults setObject:sig forKey:@"IM_SIG"];
            
        }else{
            NSLog(@"error:%@",error.localizedDescription);
            NSLog(@"%s",__func__);
        }
    }];
    
    [task resume];
}

-(void)loginIMWithId:(NSString *)userIMID andSig:(NSString *)sig{
    
    TIMLoginParam *param = [TIMLoginParam new];
    [param setIdentifier:userIMID];//服务平台管理的自有账号系统给的ID
    [param setUserSig:sig];//服务平台管理生成的SIG
    
    [param setAccountType:@"926"];
    [param setAppidAt3rd:@"1400001738"];
    [param setSdkAppId:1400001738];
    
    TIMManager *timm = [TIMManager sharedInstance];
    [timm setEnv:2];
    
    [timm setMessageListener:self];
    [timm setConnListener:self];
    [timm initSdk:1400001738];
    [timm login:param succ:^{
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:sig forKey:@"IMsig"];
        [userDefaults setObject:userIMID forKey:@"IMuserId"];
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"MSG : %@",msg);
    }];
}

-(void)sendMessage:(NSString *)message withUserId:(NSString *)userId{
    TIMConversation * c2c_conversation = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:userId];
    
    TIMTextElem * text_elem = [[TIMTextElem alloc] init];
    [text_elem setText:message];
    
    TIMMessage *timMsg = [[TIMMessage alloc]init];
    [timMsg addElem:text_elem];
    
    [c2c_conversation sendMessage:timMsg succ:^{
        NSLog(@"SendMsg Succ");
    } fail:^(int code, NSString *msg) {
        NSLog(@"SendMsg Failed:%d->%@", code, msg);
    }];
}

-(void)receiverIM:(NSTimer *)innerTimer{
    NSDictionary *userInfo = [innerTimer userInfo];
    NSString *userId = userInfo[@"receiverIMuserId"];
    
    TIMManager *timm = [TIMManager sharedInstance];
    TIMConversation *conversation = [timm getConversation:TIM_C2C receiver:userId];
    [conversation getMessage:10 last:nil succ:^(NSArray *msgs) {
        NSLog(@"getMessage : %@",msgs);
    } fail:^(int code, NSString *msg) {
        
    }];
}

#pragma mark - TIMMessageListener
-(void)onNewMessage:(NSArray *)msgs{
    NSLog(@"%@",msgs);
}

#pragma mark - TIMConnListener
-(void)onConnSucc{
    NSLog(@"onConnSucc");
}

@end
